package com.jin.crud.common.config.security;

import com.alibaba.fastjson.JSON;
import com.jin.crud.bean.LoginUser;
import com.jin.crud.common.code.HttpCodeEnum;
import com.jin.crud.common.exception.ResultException;
import com.jin.crud.common.utils.JwtUtils;
import com.jin.crud.common.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author yuxuejin
 * @Date 2021/11/25 23:13
 * @Description:
 */
//@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    JwtUtils jwtTokenUtil;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //LoginUser loginUser = tokenService.getLoginUser(request);
        //if (StringUtils.isNotNull(loginUser)) {
        //    String userName = loginUser.getUsername();
        //    // 删除用户缓存记录
        //    tokenService.delLoginUser(loginUser.getToken());
        //    // 记录用户退出日志
        //    AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        //}
        LoginUser loginUser = jwtTokenUtil.getUserDetailFromAuthContext();
        jwtTokenUtil.removeToken(loginUser.getUserId());
        ServletUtils.renderString(response, JSON.toJSONString(new ResultException(HttpCodeEnum.SUCCESS.getCode(), "退出成功")));
    }

}
